package com.FOD.fragments;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import com.FOD.clases.R;
import com.FOD.entities.User;
import com.FOD.util.EncryptMessages;

/**
 * Fragmento para dar de alta a un usuario
 * @author rafa
 *
 */
public class NewUserFragment extends Fragment {
	private static String KEY_SUCCESS = "success";
	private static String KEY_ERROR = "error";

	// Campos que el usuario llenara
	EditText nickname;
	EditText password;
	EditText confirmPass;
	EditText name;
	EditText lastName;
	EditText mail;
	Spinner user_type;
	EditText age;
	Spinner sex;
	EditText dependecy;
	EditText sport;
	EditText phone;
	EditText pathological;
	EditText non_pathological;
	View rootView;

	// Modelo del usuario
	User mUser;
	// boton para siguiente
	Button nextAction;

	public NewUserFragment(){}


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		rootView = inflater.inflate(R.layout.new_user, container, false);

		// asignamos todos los camos de la pantalla
		nickname = (EditText) rootView.findViewById(R.id.nickname_new);
		password = (EditText) rootView.findViewById(R.id.password_new);
		confirmPass = (EditText) rootView.findViewById(R.id.confirmPass_new);
		name = (EditText) rootView.findViewById(R.id.name_new);
		lastName = (EditText) rootView.findViewById(R.id.lastname_new);
		mail = (EditText) rootView.findViewById(R.id.mail_new);
		age = (EditText) rootView.findViewById(R.id.age_new);
		sex = (Spinner) rootView.findViewById(R.id.sex_new);
		dependecy = (EditText) rootView.findViewById(R.id.dependency_new);
		sport = (EditText) rootView.findViewById(R.id.sport_new);
		phone = (EditText) rootView.findViewById(R.id.phone_new);
		nextAction = (Button) rootView.findViewById(R.id.nextAction);
		user_type = (Spinner) rootView.findViewById(R.id.userType_new);
		//Asignar tipos de usuarios al Spinner userType_new
		ArrayAdapter<CharSequence> adapter_userType = ArrayAdapter.createFromResource(rootView.getContext(),R.array.users_types_spinner, android.R.layout.simple_spinner_item);
		user_type.setAdapter(adapter_userType);

		//Asignar valores de sexo al Spinner sex_new
		ArrayAdapter<CharSequence> adapter_sexType = ArrayAdapter.createFromResource(rootView.getContext(),R.array.sex_types_spinner, android.R.layout.simple_spinner_item);
		sex.setAdapter(adapter_sexType);

		// damos funcionalidad al boton de crear para intentar dar de alta al usuario
		nextAction.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				User setUser = new User();
				setUser = setUser();

				if(setUser != null){
					Bundle userToAdd = saveToBundle(setUser);
					//Siguiente pantalla
					if(setUser.getType() == 1){
						//Nuevo fragmento para siguiente accion Doctor
						Fragment fragment = new NewUserEmpleadoFragment();
						FragmentManager fragmentManager = getFragmentManager();
						fragment.setArguments(userToAdd);
						fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();						
					}else if(setUser.getType() == 2){
						//Nuevo fragmento para siguiente accion terapeuta
						Fragment fragment = new NewUserEmpleadoFragment();
						FragmentManager fragmentManager = getFragmentManager();
						fragment.setArguments(userToAdd);
						fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
					}else if(setUser.getType() == 3){
						//Nuevo fragmento para siguiente accion Paciente
						Fragment fragment = new NewUserPacienteFragment();
						FragmentManager fragmentManager = getFragmentManager();
						fragment.setArguments(userToAdd);
						fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
					}

				}else{

				}
			}
		});


		return rootView;
	}




	private User setUser(){		

		//Hacer validacion de los campos
		mUser = new User();
		mUser.setNickname(nickname.getText().toString());
		mUser.setPassword(EncryptMessages.encryptMD5(password.getText().toString()));
		mUser.setName(name.getText().toString()+" "+ lastName.getText().toString());
		mUser.setMail(mail.getText().toString());
		mUser.setSex(mUser.getConverterSexToInt(sex.getSelectedItem().toString(), rootView.getContext()));
		mUser.setDependecy(dependecy.getText().toString());
		mUser.setSport(sport.getText().toString());
		mUser.setPhone(Long.valueOf(phone.getText().toString()));
		Calendar today = new GregorianCalendar();
		mUser.setCreateDate(today.getTime());

		String userType = user_type.getSelectedItem().toString();
		if(userType.equals("Tipo de usuario")){
			//error
			mUser.setType(0);
		} else if(userType.equals("Doctor")){
			mUser.setType(1);
		}else if(userType.equals("Terapeuta")){
			mUser.setType(2);
		}else if(userType.equals("Paciente")){
			mUser.setType(3);
		}
		return mUser;
	}

	//Hide the keyboard when the Fragmenet is created
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);



	}

	public Bundle saveToBundle(User userObject){
		Bundle bundle = new Bundle();
		bundle.putParcelable("userToAdd", userObject);
		return bundle;
	}

	public void onBackPressed() {
		
	}



}

